/**
 * @type {import('vuex).Module}
 */

import { getToken, removeToken, setToken, setUserInfo } from '@/utils/auth'
import { login } from '@/api/user'

const user = {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {}
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      setToken(token)
    },
    removeToken(state) {
      state.token = null
      removeToken()
    },
    setUserInfo(state, userInfo) {
      setUserInfo(userInfo)
      state.userInfo = userInfo
    }
  },
  actions: {
    async handleLogin(ctx, payload) {
      const res = await login(payload)
      console.log(res)
      ctx.commit('setToken', res.token)
    },
    async getUserInfo(ctx, payload) {
      const res = await login(payload)
      ctx.commit('setUserInfo', res)
    },
    logOut(ctx) {
      ctx.commit('removeToken')
      ctx.commit('setUserInfo', {})
    }
  }
}

export default user
